package com.hengpeng.itfinoss.controller.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.model.Order.OrderType;
import com.hengpeng.common.util.SignatureHelper;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.constants.SystemConfigConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.en.AccountType;
import com.hengpeng.itfinbase.en.SubAccountType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.CorpOpenRequestMsg;
import com.hengpeng.itfinbase.message.partner.CorpRegisterQueryRequest;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.RegisterSource;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoStatus;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoType;
import com.hengpeng.itfinoss.constant.SystemConfigUtil;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.service.ServiceFactory;

/**
 * <pre>
 * 短息日志控制器
 * </pre>
 * @version 1.0, 2010-9-3
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController
{
	@Autowired
	private ServiceFactory serviceFactory;

	@RequestMapping(value = "/list")
	public String list(HttpServletRequest request, ModelMap map, String userName, String mobile, String type,
			String cardNumber, String trustAccountId)
	{

		UserInfoType _type = null;

		if (type != null && type.trim().length() > 0)
			_type = UserInfoType.valueOf(type);
		map.put("mobile", mobile);
		map.put("cardNumber", cardNumber);
		map.put("trustAccountId", trustAccountId);
		map.put("userName", userName);
		map.put("type", _type);
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		try
		{
			List<UserInfo> list = new ArrayList<UserInfo>();
			if (mobile != null)
			{
				ServiceResult<List<UserInfo>> result = serviceFactory.getUserInfoService().selectUserPage(userName,
						mobile, _type, cardNumber, trustAccountId, page.currentPage, page.pageSize, OrderType.DESC,
						"registerTime");
				page.setEntityCount(result.getReturnListSize());
				list = result.getReturnValue();
			}
			map.put("userList", list);
			map.put("userListPage", page);
			return "/user/list";
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return returnError(map, ex);
		}
	}

	@RequestMapping(value = "/load/{id}")
	public String load(ModelMap map, HttpServletRequest request, @PathVariable Long id)
	{
		UserInfo user = serviceFactory.getPersistService().get(UserInfo.class, id);
		if (user == null)
		{
			return returnError(map, "无法找到用户！");
		}
		map.put("user", user);
		return "/user/detail";
	}

	@RequestMapping(value = "/modify")
	public String modify(ModelMap map, HttpServletRequest request, UserInfo user)
	{

		try
		{
			user.setUpdateTime(new Date());
			user = serviceFactory.getPersistService().update(user);
			
			List<Account> accounts = serviceFactory.getAccountService().findByUserId(user.getId());
			if (accounts == null || accounts.size() < 1) {
				Account account = new Account();
				account.setAccountType(AccountType.PERSONAL);
				account.setSubAccountType(SubAccountType.MERDT);
				account.setSubAccountId("MDT000001");
				account.setUserName(user.getUserName());
				account.setAccountName(account.getSubAccountType().getText());
				account.setUserId(user.getId());
				account.setBaseMoney(0l);
				account.setBaseMoneyCollect(0l);
				account.setBaseMoneyRepay(0l);
				account.setCreateTime(new Date());
				account.setUpdateTime(new Date());
				account.setFreezeMoney(0l);
				account.setInComeMoneyCollect(0l);
				account.setInterestMoneyRepay(0l);
				account.setTotaldrawMoney(0l);
				account.setTotalfillMoney(0l);
				account.setTotalIncomeMoney(0l);
				account.setTotalInvestMoney(0l);
				account.setTotalInvestNum(0l);
				account.setTrustAccountId(user.getTrustAccountId());
				serviceFactory.getPersistService().save(account);
			}
			ServiceResult<UserInfo> result = new ServiceResult<UserInfo>(user);
			result.setMessage("用户资料修改成功");
			return returnSuccess(map, result, "/user/list");
		}
		catch (Exception e)
		{
			return returnError(map, "用户资料修改失败！");
		}
	}

	@RequestMapping(value = "/addCorp")
	public String addCorp(ModelMap map, HttpServletRequest request)
	{
		return "/user/addCorpUser";
	}
	@RequestMapping(value = "/save")
	public String save(ModelMap map, HttpServletRequest request, UserInfo user)
	{
		user.setStatus(UserInfoStatus.NORMAL);
		user.setIsEmailCheck(BoolValue.NO);
		user.setIsMobileCheck(BoolValue.NO);
		user.setIsRealNameCheck(BoolValue.NO);
		user.setRegisterTime(new Date());
		user.setRegisterFrom(RegisterSource.BACK);
		user.setUpdateTime(new Date());
		user.setLastLoginTime(new Date());
		user.setLoginFailNum(0);
		user.setLoginSucNum(0);
		user.setPwdAttach(SystemConfigUtil.getConfigValue(SystemConfigConstants.LOGIN_PASSWORD_ATTACH));
		user.setPassword(SignatureHelper.generateMD5Signture(SystemConfigUtil.getConfigValue(SystemConfigConstants.ENTERPRISE_DEFAULT_PWD) + user.getPwdAttach(),
					"utf-8"));
		
		try
		{
			user = serviceFactory.getPersistService().save(user);
			
			Account account = new Account();
			account.setAccountType(AccountType.PERSONAL);
			account.setSubAccountType(SubAccountType.MERDT);
			account.setSubAccountId("MDT000001");
			account.setUserName(user.getUserName());
			account.setAccountName(account.getSubAccountType().getText());
			account.setUserId(user.getId());
			account.setBaseMoney(0l);
			account.setBaseMoneyCollect(0l);
			account.setBaseMoneyRepay(0l);
			account.setCreateTime(new Date());
			account.setUpdateTime(new Date());
			account.setFreezeMoney(0l);
			account.setInComeMoneyCollect(0l);
			account.setInterestMoneyRepay(0l);
			account.setTotaldrawMoney(0l);
			account.setTotalfillMoney(0l);
			account.setTotalIncomeMoney(0l);
			account.setTotalInvestMoney(0l);
			account.setTotalInvestNum(0l);
			account.setTrustAccountId(user.getTrustAccountId());
			serviceFactory.getPersistService().save(account);
			
			ServiceResult<UserInfo> result = new ServiceResult<UserInfo>(user);
			result.setMessage("企业用户添加成功");
			return returnSuccess(map, result, "/user/list");
		}
		catch (Exception e)
		{
			return returnError(map, "企业用户添加失败！");
		}
	}

	@RequestMapping(value = "/open/{userId}", method = RequestMethod.POST)
	public String open(ModelMap map, HttpServletRequest request, @PathVariable String userId)
	{
		UserInfo user = serviceFactory.getPersistService().get(UserInfo.class, Long.parseLong(userId));
		map.put("user", user);
		return "/user/forOpenCorpUser";
	}

	@RequestMapping(value = "/open/submit/{userId}", method = RequestMethod.GET)
	public String openSubmit(ModelMap map, HttpServletRequest request, @PathVariable String userId) throws Exception
	{
		UserInfo user = serviceFactory.getPersistService().get(UserInfo.class, Long.parseLong(userId));
		ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
		CorpOpenRequestMsg reqMsg = new CorpOpenRequestMsg();
		reqMsg.setUserId(String.valueOf(userId));
		reqMsg.setBusiCode(user.getBusiCode());
		if (UserInfoType.GUARATOR == user.getType())
		{
			reqMsg.setGuarType("Y");
		}
		else
		{
			reqMsg.setGuarType("N");
		}
		reqMsg.setInstuCode(user.getOrganizeCode());
		reqMsg.setTaxCode(user.getTaxCode());
		reqMsg.setRealName(user.getRealName());
		reqMsg.setMerPriv(String.valueOf(userId));
		reqMsg.setPartnerTransType(PartnerTransType.CorpRegister);
		reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
		reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
		ResponseMessage response = (ResponseMessage) serviceFactory.getRemoteService().remoteTrans(reqMsg);
		result.setReturnValue(response);
		map.put("formContent", response.getOrderFormContent());
		return "/user/submitForm";
	}

	@RequestMapping(value = "/open/query")
	@ResponseBody
	public String openQuery(ModelMap map, HttpServletRequest request, String userId) throws Exception
	{
		UserInfo user = serviceFactory.getPersistService().get(UserInfo.class, Long.parseLong(userId));

		if (user.getBusiCode() == null || user.getBusiCode().trim().equals(""))
		{
			return "营业执照编号不能为空";
		}
		ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
		CorpRegisterQueryRequest reqMsg = new CorpRegisterQueryRequest();
		reqMsg.setBusiCode(user.getBusiCode());
		reqMsg.setPartnerTransType(PartnerTransType.CorpRegisterQuery);
		reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
		reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
		ResponseMessage response = serviceFactory.getRemoteService().remoteTrans(
				reqMsg);
		result.setReturnValue(response);
		return response.getRespDesc();
	}
}
